#include "znx_queue.h"

/***
 * find the middle queue element if the queue has odd number of elements
 * or the first element of the queue's second part otherwise
 */
znx_queue_t *
znx_queue_middle(znx_queue_t *queue)
{
    znx_queue_t *middle, *next;

    middle = znx_queue_head(queue);

    if (middle == znx_queue_last(queue)) {
        return middle;
    }

    next = znx_queue_head(queue);

    for ( ;; ) {
        middle = znx_queue_next(middle);

        next = znx_queue_next(next);

        if (next == znx_queue_last(queue)) {
            return middle;
        }

        next = znx_queue_next(next);

        if (next == znx_queue_last(queue)) {
            return middle;
        }
    }
}


/* the stable insertion sort */
void
znx_queue_sort(znx_queue_t *queue,
    int (*cmp)(const znx_queue_t *, const znx_queue_t *))
{
    znx_queue_t  *q, *prev, *next;

    q = znx_queue_head(queue);

    if (q == znx_queue_last(queue)) {
        return;
    }

    for (q = znx_queue_next(q); q != znx_queue_sentinel(queue); q = next) {

        prev = znx_queue_prev(q);
        next = znx_queue_next(q);

        znx_queue_remove(q);

        do {
            if (cmp(prev, q) <= 0) {
                break;
            }

            prev = znx_queue_prev(prev);

        } while (prev != znx_queue_sentinel(queue));

        znx_queue_insert_after(prev, q);
    }
}

void
znx_queue_move(znx_queue_t *src, znx_queue_t *dest) {
    if (znx_queue_empty(src)) {
        return;
    }

    if (znx_queue_empty(dest)) {
        dest->next = src->next;
        dest->prev = src->prev;
        src->next->prev = dest;
        src->prev->next = dest;
        znx_queue_init(src); // reset src
        return;
    }

    src->next->prev = dest;
    dest->next->prev = src->prev;
    src->prev->next = dest->next;
    dest->next = src->next;
    znx_queue_init(src); // reset src
}